import re

from bs4 import BeautifulSoup
from fastapi import APIRouter
from re_common.baselibrary.tools.myparsel import MParsel
from re_common.baselibrary.utils.basedict import BaseDicts
from re_common.baselibrary.utils.core.mlamada import bools_string

from apps.core.callback import default_call_back
from apps.core.global_model import ParseHtmlModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import InputInfoModel, ReturnInfo

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/step1/parse_home")
async def parse_home(input: InputInfoModel[ParseHtmlModel]):
    """
    解析首页 得到大分类
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    html = input.data.html
    xpath_dicts = {
        'bkinfo': {
            'parent': "//div[contains(@class,'category-list')]/ul/li/div",  # 解析主体
            'children': {
                'type_name': './h5/a/text()',  # 科目名称
                'page_url': './a/@href',
            }
        }
    }
    mc = MParsel(html=html)
    new_dict = mc.xpath_parsel(sel=mc.sel, xpath_selector=xpath_dicts)
    BaseDicts.get_recursive_dict(new_dict, None, default_call_back)
    rslist = new_dict["bkinfo"]["children"]
    for rs in rslist:
        rs["tagid"] = rs["page_url"].split("=")[1]
    return_info.status = bools_string(True)
    return_info.msg_code = 200
    return_info.msg = ""
    return_info.data = rslist
    return return_info.todict()

@router.post("/step2/parse_home_cnt")
async def parse_home_cnt(input: InputInfoModel[ParseHtmlModel]):
    """
    解析首页分类总数信息
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    html = input.data.html
    xpath_dicts = {
        'recount': "//div[@class='lemma_num']/text()"
    }
    mc = MParsel(html=html)
    new_dict = mc.xpath_parsel(sel=mc.sel, xpath_selector=xpath_dicts)
    BaseDicts.get_recursive_dict(new_dict, None, default_call_back)
    rs = re.findall(r'\(共(\d+)个\)', new_dict["recount"])
    if rs == None or len(rs) == 0:
        rs = 0
    else:
        rs = int(rs[0].strip())
    return_info.status = bools_string(True)
    return_info.msg_code = 200
    return_info.msg = ""
    return_info.data = {"totalnum":rs}
    return return_info.todict()
